import supApi from "@/api/pur/sup";
import orderApi from "@/api/pur/order";
import goodsApi from "@/api/pur/supgoods";
import dictApi from "@/api/system/dict";
export default {
  name: "supOrder",
  computed: {
    totalPrice() {
      let total = 0;
      this.selectList.forEach((item) => {
        total += item.goodsTotalPrice;
      });
      return total / 100;
    },
  },
  data() {
    return {
      listQuery: {
        current: 1,
        size: 20,
        criteria: {
          orderNum: "",
          supplierName: "",
          supplierId: "",
          orderStatus: "",
          storageStatus: "",
          expressId: "",
          purchaser: "",
          createTime: "",
        },
      },
      listGoodsQuery: {
        current: 1,
        size: 20,
        criteria: {
          name: "",
          supId: "",
          type: "",
          status: 0,
        },
      },

      total: 0,
      totalGoods: 0,
      list: null,
      listGoods: null,
      listLoading: true,
      listGoodsLoading: true,
      listSup: null,
      formTitle: "",
      formVisible: false,
      addForm: {
        createTime: "",
        supplierId: "",
        purchaser: "",
        remark: "",
      },
      rules: {
        createTime: [
          { required: true, message: "请选择采购时间", trigger: "blur" },
        ],
        supplierId: [
          { required: true, message: "请选择供应商", trigger: "blur" },
        ],
        purchaser: [
          { required: true, message: "请输入采购人", trigger: "blur" },
          {
            min: 2,
            max: 20,
            message: "长度在 2 到 20 个字符",
            trigger: "blur",
          },
        ],
      },
      baseUrl: process.env.VUE_APP_BASE_API,
      drawer: false,
      goodsType: null,
      selectList: [],
      multipleSelection: [],
      infoVisible: false,
      infoForm: "",
      infoGoodsList: [],
      listOrderGoodsLoading: true,
    };
  },

  filters: {
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "gray",
        deleted: "danger",
      };
      return statusMap[status];
    },
  },
  created() {
    this.init();
    this.getTypeDict();
  },
  methods: {
    init() {
      this.fetchData();
      this.getOnlySupNameList();
    },
    fetchData() {
      this.listLoading = true;
      orderApi.getList(this.listQuery).then((response) => {
        this.list = response.data.records;
        this.total = response.data.total;
        this.listLoading = false;
      });
    },
    fetchDataGoods() {
      this.listGoodsLoading = true;
      goodsApi.listSupGoodsPage(this.listGoodsQuery).then((response) => {
        this.listGoods = response.data.records;
        this.listGoodsLoading = false;
        this.totalGoods = response.data.total;
      });
    },
    formatDate(originVal) {
      const dt = new Date(originVal);
      const y = dt.getFullYear();
      const m = (dt.getMonth() + 1 + "").padStart(2, "0");
      const d = (dt.getDate() + "").padStart(2, "0");
      const hh = (dt.getHours() + "").padStart(2, "0");
      const mm = (dt.getMinutes() + "").padStart(2, "0");
      const ss = (dt.getSeconds() + "").padStart(2, "0");
      return `${y}-${m}-${d} ${hh}:${mm}:${ss}`;
    },
    search() {
      this.listQuery.current = 1;
      this.fetchData();
    },

    reset() {
      Object.keys(this.listQuery.criteria).forEach((key) => {
        this.listQuery.criteria[key] = "";
      });
      this.listQuery.current = 1;
      this.fetchData();
    },
    handleFilter() {
      this.listQuery.current = 1;
      this.fetchData();
    },
    handleClose() {},
    fetchNext() {
      this.listQuery.current = this.listQuery.current + 1;
      this.fetchData();
    },

    fetchPrev() {
      this.listQuery.current = this.listQuery.current - 1;
      this.fetchData();
    },

    fetchPage(page) {
      this.listQuery.current = page;
      this.fetchData();
    },

    changeSize(limit) {
      this.listQuery.size = limit;
      this.fetchData();
    },

    searchGoods() {
      this.listGoodsQuery.current = 1;
      this.fetchDataGoods();
    },
    resetGoods() {
      Object.keys(this.listGoodsQuery.criteria).forEach((key) => {
        if (key != "supId") {
          this.listGoodsQuery.criteria[key] = "";
        }
      });
      this.listGoodsQuery.current = 1;
      this.fetchDataGoods();
    },
    fetchNextGoods() {
      this.listGoodsQuery.current = this.listGoodsQuery.current + 1;
      this.fetchDataGoods();
    },
    fetchPrevGoods() {
      this.listGoodsQuery.current = this.listGoodsQuery.current - 1;
      this.fetchDataGoods();
    },
    changeSizeGoods(limit) {
      this.listGoodsQuery.size = limit;
      this.fetchDataGoods();
    },
    fetchPageGoods(page) {
      this.listGoodsQuery.current = page;
      this.fetchDataGoods();
    },
    formatDate(originVal) {
      const dt = new Date(originVal);
      const y = dt.getFullYear();
      const m = (dt.getMonth() + 1 + "").padStart(2, "0");
      const d = (dt.getDate() + "").padStart(2, "0");
      const hh = (dt.getHours() + "").padStart(2, "0");
      const mm = (dt.getMinutes() + "").padStart(2, "0");
      const ss = (dt.getSeconds() + "").padStart(2, "0");
      return `${y}-${m}-${d} ${hh}:${mm}:${ss}`;
    },
    formatTime(originVal) {
      const dt = new Date(originVal);
      const y = dt.getFullYear();
      const m = (dt.getMonth() + 1 + "").padStart(2, "0");
      const d = (dt.getDate() + "").padStart(2, "0");
      return `${y}-${m}-${d}`;
    },
    handleCurrentChange(currentRow, oldCurrentRow) {
      this.selRow = currentRow;
    },
    getOnlySupNameList() {
      supApi.getOnlySupNameList().then((response) => {
        this.listSup = response.data;
      });
    },
    addOrderBefore() {
      this.formTitle = "新增采购单";
      this.formVisible = true;
    },
    addGoods() {
      if (!this.addForm.supplierId) {
        this.$message({
          message: "请先选择供应商",
          type: "warning",
        });
        return;
      }

      this.drawer = true;
      this.listGoodsQuery.criteria.supId = this.addForm.supplierId;
      this.fetchDataGoods();
      //初始化选中行
      this.$refs.multipleSelection.clearSelection();
      if (this.selectList.length > 0) {
        this.selectList.forEach((row) => {
          this.$refs.multipleSelection.toggleRowSelection(row);
        });
      }
      //查询商品列表
    },
    getTypeDict() {
      // 从后台获取字典列表
      let dictName = "商品类型";
      dictApi.getDicts(dictName).then((response) => {
        this.goodsType = response.data[0].children ?? [];
      });
    },
    getTypeValueDict(num) {
      const arr = this.goodsType;
      if (arr) {
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].num == num) {
            return arr[i].name;
          }
        }
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //确认选中
    confirmSelect() {
      let arr = [];
      this.multipleSelection.forEach((row) => {
        let item = this.selectList;
        let obj = {};
        obj.goodsId = row.id;
        obj.id = row.id;
        obj.type = row.type;
        obj.name = row.name;
        obj.specification = row.specification;
        obj.goodsPrice = row.price;
        obj.priceUnit = row.priceUnit;
        obj.goodsNum = 1;
        obj.goodsTotalPrice = row.price;
        if (item) {
          item.forEach((row1) => {
            if (row.id == row1.goodsId) {
              //有则保存原来的数量和总价
              obj.goodsNum = row1.goodsNum;
              obj.goodsTotalPrice = row1.goodsTotalPrice;
            }
          });
        }
        arr.push(obj);
      });
      this.selectList = arr;
      this.drawer = false;
    },

    handleChangeTotal(value) {
      value.goodsTotalPrice = value.goodsNum * value.goodsPrice;
    },
    clearnSelectList() {
      this.selectList = [];
    },
    deleteGoods(row) {
      let index = this.selectList.findIndex(
        (item) => item.goodsId === row.goodsId
      );
      if (index !== -1) {
        this.selectList.splice(index, 1);
      }
    },
    saveOrder() {
      var self = this;
      this.$refs["addForm"].validate((valid) => {
        if (valid) {
          if (this.selectList.length > 0) {
            let form = self.addForm;
            form.goodsList = this.selectList;
            orderApi.save(form).then((response) => {
              this.$message({
                message: "提交成功",
                type: "success",
              });
              //刷新
              self.formVisible = false;
              self.fetchData();
              self.selectList = [];
              self.clearobj(self.addForm);
            });
          } else {
            this.$message({
              message: "请选择商品",
              type: "warning",
            });
          }
        }
      });
    },
    clearobj(obj) {
      Object.keys(obj).forEach((key) => {
        if (key != "supId") {
          obj[key] = "";
        }
      });
    },
    viewOrder(row) {
      this.infoForm = row;
      this.infoVisible = true;
      //根据订单Id获取商品信息
      orderApi.getGoodsListByOrderId(row.id).then((response) => {
        this.infoGoodsList = response.data;
      });
    },
    copyTextToClipboard(text) {
      if (!navigator.clipboard) {
        // Clipboard API not available
        console.error("Clipboard API not available");
        return;
      }
      navigator.clipboard
        .writeText(text)
        .then(() => {
          this.$message({
            message: "复制成功",
            type: "success",
          });
        })
        .catch((err) => {
          this.$message({
            message: "复制失败",
            type: "error",
          });
        });
    },
    generNum() {
      return Math.floor(Math.random() * 20);
    },
    backOrder(orderId) {
      orderApi.backOrder(orderId).then((response) => {
        this.$message({
          message: "退货已申请",
          type: "success",
        });
        this.fetchData();
      });
    },
    flushOrder() {
      orderApi.flushOrder().then((response) => {
        this.$message({
          message: "刷新成功",
          type: "success",
        });
        this.fetchData();
      });
    },
  },
};
